import debounce from 'lodash/debounce';
import React from 'react';

import {
  ITerminalController,
  ITerminalError,
  ITerminalErrorService,
  ITerminalGroupViewService,
  ITerminalNetwork,
  IWidget,
} from '../../common';

import ResizeView, { ResizeDirection } from './resize.view';
import styles from './terminal.module.less';
import TerminalWidget from './terminal.widget';

import '@xterm/xterm/css/xterm.css';
import { useAutorun } from '../../../react-hooks/react-hooks';
import { useEventEffect } from '../../../react-hooks';
import { FRAME_THREE } from '../../../utils';

export interface TerminalViewProps {
  controller: ITerminalController;
  errorService: ITerminalErrorService;
  view: ITerminalGroupViewService;
}

const TerminalView: React.FC<TerminalViewProps> = ({
  controller,
  errorService,
  view,
}) => {
  const wrapperRef = React.useRef<HTMLDivElement | null>(null);

  // 当前分组 id
  const currentGroupId = useAutorun(view.currentGroupId);
  // 当前分组索引
  const currentGroupIndex = useAutorun(view.currentGroupIndex);
  // 所有分组
  const groups = useAutorun<any[]>(view.groups);

  // 终端错误信息
  const [errors, setErrors] = React.useState(errorService.errors);
  // 防抖处理错误变化
  const func = debounce(() => {
    setErrors(errorService.errors);
  }, FRAME_THREE);
  useEventEffect(errorService.onErrorsChange, func);

  // 渲染单个终端 widget
  const renderWidget = React.useCallback(
    (widget: IWidget, index: number) => {
      const client = controller.findClientFromWidgetId(widget.id);
      let error: ITerminalError | undefined;
      if (client) {
        errors.get(client.id);
      } else {
        error = errors.get(widget.id);
      }

      return (
        <TerminalWidget
          show={currentGroupIndex === index}
          error={error}
          widget={widget}
          errorService={errorService}
          view={view}
        />
      );
    },
    [currentGroupIndex, controller, errors, view]
  );

  // 组件挂载时初始化 context key 和视图就绪
  React.useEffect(() => {
    if (wrapperRef.current) {
      controller.viewReady.resolve();
    }
  }, [wrapperRef.current, groups, controller]);

  return (
    <div
      ref={wrapperRef}
      className={styles.terminalWrapper}
      data-group-current={currentGroupId}
    >
      {/* 渲染所有终端分组 */}
      {groups.map((group, index) => {
        if (!group.activated.get()) {
          return null;
        }

        return (
          <div
            data-group-rendered={group.activated.get()}
            key={`terminal-${group.id}`}
            style={{ display: currentGroupIndex === index ? 'block' : 'none' }}
            className={styles.group}
            onFocus={controller.focus.bind(controller)}
            onBlur={controller.blur.bind(controller)}
            onContextMenu={controller.onContextMenu.bind(controller)}
          >
            {/* 拖拽分割视图 */}
            <ResizeView
              shadow={true}
              useFlex={false}
              direction={ResizeDirection.horizontal}
              group={group}
              draw={(widget: IWidget) => renderWidget(widget, index)}
            />
          </div>
        );
      })}
    </div>
  );
};

export default TerminalView;
